<template>
  <a-drawer
    width="92%"
    placement="right"
    :visible="visible"
    :after-visible-change="afterVisibleChange"
    @close="onClose"
    title="分账规则设置"
    class="form-drawer form-card"
  >
    <a-form-model
      ref="ruleForm"
      :model="form"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      class="form-model"
    >
      <div class="ant-descriptions-title">分账店铺</div>
      <a-form-model-item label="分账店铺" prop="region" class="is-required">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-model-item prop="brandCode">
              <brand-select v-model="form.brandCode" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="form.brandCode">
            <a-form-model-item prop="storeCode">
              <store-select v-model="form.storeCode" :brandCode.sync="form.brandCode" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model-item>
      <a-form-model-item
        label="投资项目"
        prop="projectCode"
        v-if="form.brandCode && form.storeCode"
      >
        <project-select
          v-model="form.projectCode"
          :brandCode.sync="form.brandCode"
          @change="projectChange"
        />
        <div class="form-tip none-icon" v-if="form.performanceStartTime">
          履约时间：{{ form.performanceStartTime + '～' + form.performanceEndTime }}
        </div>
      </a-form-model-item>
      <template v-if="form.projectCode">
        <div class="ant-descriptions-title">分账接收账户</div>
        <a-table :columns="columns" :data-source="receivableSource" :pagination="false">
          <div slot="ratio" slot-scope="text, record">
            <a-input v-model="record.ratio" allow-clear />
          </div>
          <div slot="firstRatio" slot-scope="text, record">
            <a-input v-model="record.firstRatio" allow-clear />
          </div>
          <div slot="secondRatio" slot-scope="text, record">
            <a-input v-model="record.secondRatio" allow-clear />
          </div>
          <div slot="thirdRatio" slot-scope="text, record">
            <a-input v-model="record.thirdRatio" allow-clear />
          </div>
          <div slot="fourthRatio" slot-scope="text, record">
            <a-input v-model="record.fourthRatio" allow-clear />
          </div>
          <div slot="fifthRatio" slot-scope="text, record">
            <a-input v-model="record.fifthRatio" allow-clear />
          </div>
          <div slot="sixthRatio" slot-scope="text, record">
            <a-input v-model="record.sixthRatio" allow-clear />
          </div>
        </a-table>
        <div class="flex-center" :style="{ margin: '20px 0' }">
          <div class="ant-descriptions-title mb-none">其他分账接收账户</div>
          <a-button type="primary" size="small" @click="addOther" :style="{ marginLeft: '35px' }">
            添加其他分账接收方账户
          </a-button>
        </div>
        <a-table :columns="otherColumns" :data-source="otherSource" :pagination="false">
          <div slot="receivableName" slot-scope="text, record">
            <a-input v-model="record.receivableName" allow-clear />
          </div>
          <div slot="receivableAccount" slot-scope="text, record">
            <a-input v-model="record.receivableAccount" allow-clear />
          </div>
          <div slot="ratio" slot-scope="text, record">
            <a-input v-model="record.ratio" allow-clear />
          </div>
          <div slot="firstRatio" slot-scope="text, record">
            <a-input v-model="record.firstRatio" allow-clear />
          </div>
          <div slot="secondRatio" slot-scope="text, record">
            <a-input v-model="record.secondRatio" allow-clear />
          </div>
          <div slot="thirdRatio" slot-scope="text, record">
            <a-input v-model="record.thirdRatio" allow-clear />
          </div>
          <div slot="fourthRatio" slot-scope="text, record">
            <a-input v-model="record.fourthRatio" allow-clear />
          </div>
          <div slot="fifthRatio" slot-scope="text, record">
            <a-input v-model="record.fifthRatio" allow-clear />
          </div>
          <div slot="sixthRatio" slot-scope="text, record">
            <a-input v-model="record.sixthRatio" allow-clear />
          </div>
          <span slot="action" slot-scope="text, record, index">
            <a-popconfirm
              title="是否确定删除此规则?"
              ok-text="确认"
              cancel-text="取消"
              @confirm="delHandler(index)"
            >
              <a-button type="link">删除</a-button>
            </a-popconfirm>
          </span>
        </a-table>
      </template>
    </a-form-model>
    <a-form-model-item>
      <a-button style="margin-left: 10px" @click="onClose"> 取消 </a-button>
      <a-button type="primary" @click="onSubmit" :loading="submitLoading"> 确认 </a-button>
    </a-form-model-item>
  </a-drawer>
</template>

<script>
import { ruleReceivableAccount, ruleAddOrEdit, ruleDetail } from '@/api/subject'
import brandSelect from '@/myComponents/brand-select'
import projectSelect from '@/myComponents/project-select'
import storeSelect from '@/myComponents/store-select'
const columns = [
  {
    title: '分账接收方',
    dataIndex: 'receivableName'
  },
  {
    title: '分账接收方账户',
    dataIndex: 'receivableAccount'
  },
  {
    title: '未回本前分账比例（万分之）',
    dataIndex: 'ratio',
    scopedSlots: { customRender: 'ratio' }
  },
  {
    title: '回本后分账比例（万分之）',
    children: [
      {
        title: '第1到120个自然日',
        dataIndex: 'firstRatio',
        scopedSlots: { customRender: 'firstRatio' }
      },
      {
        title: '第121到150个自然日',
        dataIndex: 'secondRatio',
        scopedSlots: { customRender: 'secondRatio' }
      },
      {
        title: '第151到180个自然日',
        dataIndex: 'thirdRatio',
        scopedSlots: { customRender: 'thirdRatio' }
      },
      {
        title: '第181到210个自然日',
        dataIndex: 'fourthRatio',
        scopedSlots: { customRender: 'fourthRatio' }
      },
      {
        title: '第211到240个自然日',
        dataIndex: 'fifthRatio',
        scopedSlots: { customRender: 'fifthRatio' }
      },
      {
        title: '第241个自然日及之后',
        dataIndex: 'sixthRatio',
        scopedSlots: { customRender: 'sixthRatio' }
      }
    ]
  }
]
const otherColumns = [
  {
    title: '分账接收方',
    dataIndex: 'receivableName',
    scopedSlots: { customRender: 'receivableName' }
  },
  {
    title: '分账接收方账户',
    dataIndex: 'receivableAccount',
    scopedSlots: { customRender: 'receivableAccount' }
  },
  {
    title: '未回本前分账比例（万分之）',
    dataIndex: 'ratio',
    scopedSlots: { customRender: 'ratio' }
  },
  {
    title: '回本后分账比例（万分之）',
    children: [
      {
        title: '第1到120个自然日',
        dataIndex: 'firstRatio',
        scopedSlots: { customRender: 'firstRatio' }
      },
      {
        title: '第121到150个自然日',
        dataIndex: 'secondRatio',
        scopedSlots: { customRender: 'secondRatio' }
      },
      {
        title: '第151到180个自然日',
        dataIndex: 'thirdRatio',
        scopedSlots: { customRender: 'thirdRatio' }
      },
      {
        title: '第181到210个自然日',
        dataIndex: 'fourthRatio',
        scopedSlots: { customRender: 'fourthRatio' }
      },
      {
        title: '第211到240个自然日',
        dataIndex: 'fifthRatio',
        scopedSlots: { customRender: 'fifthRatio' }
      },
      {
        title: '第241个自然日及之后',
        dataIndex: 'sixthRatio',
        scopedSlots: { customRender: 'sixthRatio' }
      }
    ]
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: '',
  components: { brandSelect, projectSelect, storeSelect },
  data() {
    return {
      visible: false,
      form: {},
      submitLoading: false,
      labelCol: { span: 2 },
      wrapperCol: { span: 14 },
      rules: {
        projectCode: [{ required: true, message: '请选择投资项目', trigger: 'change' }],
        brandCode: [{ required: true, message: '请选择品牌', trigger: 'change' }],
        storeCode: [{ required: true, message: '请选择店铺', trigger: 'change' }]
      },
      receivableSource: [],
      columns,
      receivableValidate: {},
      // 其他分账接收账户
      otherColumns,
      otherSource: [],
      otherValidate: {}
    }
  },
  methods: {
    projectChange(val) {
      this.form.performanceStartTime = val.performanceStartTime
      this.form.performanceEndTime = val.performanceEndTime
      if (val.code) {
        ruleReceivableAccount({ projectCode: val.code }).then((resp) => {
          this.receivableSource = resp.data
        })
      } else {
        this.receivableSource = []
      }
    },
    otherReceivableValidate() {
      let validateMsg = '',
        validateIndex = 0,
        validateKey = '',
        flag = true
      let validKeys = this.columns[this.columns.length - 1].children.map((v) => v.dataIndex)

      this.otherSource.some((v1) => {
        if (!v1.receivableName) {
          validateMsg = '请输入分账接收方'
          // validateIndex = index
          validateKey = 'receivableName'
          flag = false
          return true
        }

        if (!v1.receivableAccount) {
          validateMsg = '请输入分账接收方账户'
          // validateIndex = index
          validateKey = 'receivableAccount'
          flag = false
          return true
        }

        if (!v1.ratio) {
          validateMsg = '请输入分账比例'
          // validateIndex = index
          validateKey = 'ratio'
          flag = false
          return true
        }

        if (v1.ratio && !/^[1-9]\d*$/.test(v1.ratio)) {
          validateMsg = '请输入正整数'
          // validateIndex = index
          validateKey = 'ratio'
          flag = false
          return true
        }
        for (let i = 0; i < validKeys.length; i++) {
          const el = validKeys[i]
          if (!v1[el]) {
            flag = false
            // validateIndex = index
            break
          } else if (v1[el] && !/^[1-9]\d*$/.test(v1[el])) {
            flag = false
            // validateIndex = index
            break
          }
        }
        return !flag
      })
      this.otherValidate = { validateIndex, validateKey }

      return flag
    },
    receivableValidateFn() {
      let validateMsg = '',
        validateIndex = 0,
        validateKey = '',
        flag = true
      let validKeys = this.columns[this.columns.length - 1].children.map((v) => v.dataIndex)
      this.receivableSource.some((v1) => {
        if (!v1.ratio) {
          validateMsg = '请输入分账比例'
          // validateIndex = index
          validateKey = 'ratio'
          flag = false
          return true
        }

        if (v1.ratio && !/^[1-9]\d*$/.test(v1.ratio)) {
          validateMsg = '请输入正整数'
          // validateIndex = index
          validateKey = 'ratio'
          flag = false
          return true
        }

        for (let i = 0; i < validKeys.length; i++) {
          const el = validKeys[i]
          if (!v1[el]) {
            flag = false
            // validateIndex = index
            break
          } else if (v1[el] && !/^[1-9]\d*$/.test(v1[el])) {
            flag = false
            // validateIndex = index
            break
          }
        }
        return !flag
      })
      this.receivableValidate = { validateIndex, validateKey }
      return flag
    },
    addOther() {
      let validateMsg = this.otherReceivableValidate()
      if (!validateMsg) {
        this.$notification['error']({
          message: '错误提示',
          description: "请选择检查其他分账接收方账户信息是否完善"
        })
      } else {
        this.otherSource.push({
          receivableName: '',
          receivableAccount: '',
          ratio: '',
          firstRatio:'',
          secondRatio:'',
          thirdRatio:'',
          fourthRatio:'',
          fifthRatio:'',
          sixthRatio:''
        })
      }
    },
    delHandler(index) {
      this.otherSource.splice(index, 1)
    },
    onSubmit() {
      const vm = this
      this.$refs.ruleForm.validate((valid) => {
        let receivableValid = vm.receivableValidateFn()
        let otherValid = vm.otherReceivableValidate()
        if (valid && receivableValid && otherValid) {
          vm.submitLoading = true
          const data = vm.form
          data.accountList = [
            ...vm.receivableSource.map((v) => {
             return { ...v}
           }),
            ...vm.otherSource.map((v) => {
              return { ...v, type: '3' }
            })
          ]
          ruleAddOrEdit(vm.form)
            .then(() => {
              vm.$notification['success']({
                message: '提示',
                description: `${vm.form.id ? '编辑' : '新增'}成功`
              })
              vm.onClose()
              vm.submitLoading = false
              vm.$emit('on-submit')
            })
            .catch(() => {
              vm.submitLoading = false
            })
        } else {
          vm.$notification['error']({
            message: '错误提示',
            description: '请选择检查分账规则设置是否完善'
          })
          return false
        }
      })
    },
    resetForm() {
      this.form = {}
      this.$refs.ruleForm.resetFields()
      this.otherSource = []
      this.receivableSource = []
    },
    afterVisibleChange(visible) {
      if (!visible) {
        this.form = {}
        this.otherSource = []
        this.receivableSource = []
      }
    },
    onClose() {
      this.visible = false
    },
    open(record) {
      if (record && record.id) {
        ruleDetail(record.id).then((resp) => {
          this.receivableSource = resp.data.accountList
          this.otherSource = resp.data.otherAccountList
          this.form = resp.data
          this.visible = true
        })
      } else {
        this.visible = true
      }
    }
  }
}
</script>

<style scoped lang="less">
.mb-none {
  margin-bottom: 0;
}
.form-drawer {
  .form-model {
    height: calc(100vh - 138px);
    .validate /deep/.ant-input {
      border-color: red;
    }
  }
}
</style>
